# -*- coding: utf-8 -*-
""" Handler zum Eingeben von einzelnen Quizz-Aufgaben. """
# appengine imports
from google.appengine.ext import db

#python imports
import cgi, sys, hashlib
from datetime import datetime

#local imports
from baserequesthandler import BaseRequestHandler
from models import Frage, Antwort
from utils import get_key_name

erlaubte_benutzer = {'orges': '123quizz321'}

class Handler(BaseRequestHandler):
  def get(self):
    template_values = {
    }
    self.generate('frage/eingabe.html', template_values)
    return

  def post(self):
    email = cgi.escape(self.request.get('titel')).encode('utf-8')
    titel = cgi.escape(self.request.get('titel')).encode('utf-8')
    text = cgi.escape(self.request.get('text'))
    text = text.replace('\n','<br/>').encode('utf-8') 

    if len(text) == 0 or len(titel) == 0:
      self.redirect('/')
      return

    t = '%s %s' % (titel, text)
    if self.is_spam(t):
      self.redirect('/')
      return

    
    prefix = '%s %s %s %s' % (datetime.now(), 
                              self.request.remote_addr, 
                               titel, text)
    url_key = get_key_name(method='md5', prefix=prefix)
    key = get_key_name(method='sha256', prefix='frage', akey=url_key)
    frage = Frage.get_by_key_name(key)
    if frage is not None:
      self.error(403)
      self.response.out.write('Die Frage ist schon vorhanden')
      return
    else:
      frage = Frage.get_or_insert(key)
      frage.url_key = url_key
      frage.antworten = []
      frage.gefaellt = 0
      frage.beantwortet = False
      frage.titel = titel.decode('utf-8')
      frage.text = text.decode('utf-8')
      frage.email = email.decode('utf-8')
      frage.put()
      self.redirect('/frage/%s' % url_key)
      return


     



